package com.gt.task;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * RestTemplate日志打印
 */
@Service
public class RestTemplatePrintLog implements RestTemplateTask {

    final static Logger log = LoggerFactory.getLogger(RestTemplatePrintLog.class);

    @Override
    public void execute(HttpRequest request, ClientHttpResponse response, byte[] body, JSONObject args) {
        try {
            traceRequest(request,body);
            traceResponse(response,args);
        }catch (Exception e){
            log.error("RestTemplate日志打印异常",e);
        }
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        log.info("===========================request begin================================================");
        log.info("URI         : {}", request.getURI());
        log.info("Method      : {}", request.getMethod());
        log.info("Headers     : {}", request.getHeaders() );
        log.info("Request body: {}", new String(body, "UTF-8"));
        log.info("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response, JSONObject args) throws IOException {
        log.info("============================response begin==========================================");
        log.info("Status code  : {}", response.getStatusCode());
        log.info("Status text  : {}", response.getStatusText());
        log.info("Headers      : {}", response.getHeaders());
        log.info("Time Consuming: {}", args.getLong("timeConsuming"));
        log.info("Response body: {}", getResponseBody(response));
        log.info("=======================response end=================================================");
    }

    /**
     * 获取相应题内容
     * @param response
     * @return
     * @throws IOException
     */
    public static String getResponseBody(ClientHttpResponse response)throws IOException {
        InputStream body = response.getBody();
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        return inputStringBuilder.toString();
    }

}
